package persistence.daos;

import java.util.List;

import model.proveedor.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import persistence.HibernateUtil;

public class HbtProveedorDAO {

	private static HbtProveedorDAO instancia = null;
	private static SessionFactory sf = null;

	public static HbtProveedorDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new HbtProveedorDAO();
		} 
		return instancia;
	}
	
	public void grabarProveedor(Proveedor proveedor){
		Session session = beginTransaction();
		session.persist(proveedor);	
		commitTransaction(session);
	} 
	
	public void borrarProveedor(Proveedor proveedor){
		Session session = beginTransaction();
		session.delete(proveedor);
		commitTransaction(session);
	} 
	
	public void actualizarProveedor(Proveedor proveedor){
		Session session = beginTransaction();
		session.update(proveedor);
		commitTransaction(session);
	} 
	
	public Proveedor obtenerProveedorPorCuit(String nroCuit){
		Session session = sf.openSession();
		Proveedor proveedor = (Proveedor)session.createQuery("from Proveedor where nroCuit = ?")
				.setString(0, nroCuit)
				.uniqueResult();
		session.close();
		return proveedor;
	} 
	
	public Proveedor obtenerProveedorPorCodigo(int codigo){
		Session session = sf.openSession();
		Proveedor proveedor = (Proveedor)session.createQuery("from Proveedor where codigo = ?")
				.setInteger(0, codigo)
				.uniqueResult();
		session.close();
		return proveedor;
	}
	
	@SuppressWarnings("unchecked")
	public List<Proveedor> obtenerProveedores(){
		Session session = sf.openSession();
		List<Proveedor> proveedores = session.createQuery("from Proveedores").list();
		session.close();
		return proveedores;
	}

	private Session beginTransaction()
	{
		Session session = sf.openSession();
		session.beginTransaction();
		return session;
	}
	
	private void commitTransaction(Session session)
	{
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
}
